//
//  BannerUseScrollViewController.swift
//  TestBanner
//
//  Created by tiantengfei on 2016/12/22.
//  Copyright © 2016年 田腾飞. All rights reserved.
//

import UIKit

class BannerUseScrollView: UIView,UIScrollViewDelegate {
    //定义一个闭包类型
    typealias selBlock = (Int) -> Void
    //声明一个变量
    var selBtnBack: selBlock?
    //定义一个方法,方法的参数为和swiftBlock类型一致的闭包,并赋值给callBack
    func callSelBlock(block: @escaping selBlock) {
        selBtnBack = block
    }

    var imageCount = 0
    var scrollView: UIScrollView!
    var pageView: UIPageControl!
    var timer: Timer?
    var images = [UIImage?]()
    var isLoadUrl = false
    var urls = [URL?]()
    var imagewidth : CGFloat = 0.0
    var imageheight : CGFloat = 0.0
    
    var isSignel = false
    
    override func draw(_ rect: CGRect) {
        if timer != nil {
            return
        }
        setupViews(rect: rect)
        addTimer()
    }
    
    
    func setupViews(rect: CGRect) {
//        if #available(iOS 11.0, *) {
//        } else {
//        automaticallyAdjustsScrollViewInsets = false
//        }
        if isLoadUrl {
            imageCount = urls.count
        }
        else {
            imageCount = images.count
        }
        
//        do {
            scrollView = UIScrollView(frame: CGRect(x: (rect.width - imagewidth)/2, y: 0, width: imagewidth, height: imageheight))
            scrollView.delegate = self
//            scrollView.contentInset = .init(top: 0, left: 0, bottom: 0, right: (rect.width - imagewidth))
            scrollView.clipsToBounds = false
            scrollView.backgroundColor = .white
            self.addSubview(scrollView)
//        }
        
//        do {
            pageView = UIPageControl(frame: CGRect(x: 0, y: rect.height - 25, width: rect.width, height: 30))
            self.addSubview(pageView)
            pageView.numberOfPages = imageCount
            pageView.currentPage = 0
            pageView.pageIndicatorTintColor = .clear
            pageView.currentPageIndicatorTintColor = .x999999
            pageView.customPageControl(dotBorderColor: .x999999, dotBorderWidth: 1.0)
//        }
        
        do {
            /// 只使用5个UIImageView，这里面使用取模运算。
            if isLoadUrl {
                for index in 0..<5 {
                    let imageView = UIImageView(frame: CGRect(x: CGFloat(index) * imagewidth,
                                                              y: 0, width: imagewidth, height: imageheight))
                    imageView.sd_setImage(with: urls[((index - 2 + imageCount) % imageCount)], completed: nil)
                    if index != 2 {
                        imageView.transform = CGAffineTransform(scaleX: 0.86, y: 0.86);
                    }
                    else {
                        scrollView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didSelsctCurrent(tap:))))
//                        imageView.drawButton(title: "BUTTON", titleColor: .red, fontSize: 15) { (make) in
//                            make.left.right.top.bottom.equalToSuperview()
//                        }.addTarget(self, action: #selector(didSelsctCurrent(btn:)), for: .touchUpInside)
                    }
                    imageView.layer.cornerRadius = 5
                    imageView.clipsToBounds = true
                    scrollView.addSubview(imageView)
                }
            }
            else {
                            for index in 0..<5 {
                                let imageView = UIImageView(frame: CGRect(x: CGFloat(index) * imagewidth,
                                                                          y: 0, width: imagewidth, height: imageheight))
                                imageView.image = images[((index - 2 + imageCount) % imageCount)]
                //                imageView.transform = CGAffineTransform(translationX: 0, y: -10);
                                if index != 2 {
                                    imageView.transform = CGAffineTransform(scaleX: 0.86, y: 0.86);
                                }
                                imageView.layer.cornerRadius = 5
                                imageView.clipsToBounds = true
                                scrollView.addSubview(imageView)
                            }
            }
        }
        
        do {
            scrollView.contentSize = CGSize(width: imagewidth * 5, height: 0)
            scrollView.contentOffset = CGPoint(x: imagewidth*2, y: 0)
            scrollView.isPagingEnabled = true
            scrollView.showsHorizontalScrollIndicator = false
            scrollView.showsVerticalScrollIndicator = false
        }
    }
    
    /// 添加timer
    func addTimer() {
        if isSignel {
            scrollView.isScrollEnabled = false
            return
        }
        scrollView.isScrollEnabled = true
        /// 利用这种方式添加的timer 如果有列表滑动的话不会调用这个timer，因为当前runloop的mode更换了
//        timer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true, block: { [weak self] (timer) in
//            self?.nextImage()
//        })
        removeTimer()
        
        if #available(iOS 10.0, *) {
            timer = Timer(timeInterval: 2, repeats: true, block: { [weak self] _ in
                self?.nextImage()
            })
        } else {
            // Fallback on earlier versions
        }
        
        guard let timer = timer else {
            return
        }
        RunLoop.current.add(timer, forMode: .common)
    }
    
    func removeTimer() {
        timer?.invalidate()
        timer = nil
    }
    
    /// 下一个图片
    func nextImage() {
        if pageView.currentPage == imageCount - 1 {
            pageView.currentPage = 0
        } else {
            pageView.currentPage += 1
        }
        let contentOffset = CGPoint(x: imagewidth * 3, y: 0)
        scrollView.setContentOffset(contentOffset, animated: true)

//        UIView.animate(withDuration: 0.3, animations: {
//            self.scrollView.subviews[2].transform = CGAffineTransform(scaleX: 0.86, y: 0.86);
//            self.scrollView.subviews[3].transform = CGAffineTransform(scaleX: 1, y: 1);
//        }, completion: { (comple) in
//        })
    }
    
    /// 上一个图片
    func preImage() {
        if pageView.currentPage == 0 {
            pageView.currentPage = imageCount - 1
        } else {
            pageView.currentPage -= 1
        }
        
        let contentOffset = CGPoint(x: imagewidth, y: 0)
        scrollView.setContentOffset(contentOffset, animated: true)
        
//        UIView.animate(withDuration: 0.3, animations: {
//            self.scrollView.subviews[2].transform = CGAffineTransform(scaleX: 0.86, y: 0.86);
//            self.scrollView.subviews[1].transform = CGAffineTransform(scaleX: 1, y: 1);
//        }, completion: { (comple) in
//        })
    }
    
    /// 重新加载图片，重新设置5个imageView
    func reloadImage() {
        let currentIndex = pageView.currentPage
        let nextIndex = (currentIndex + 1) % imageCount
        let nextIndex1 = (currentIndex + 2) % imageCount
        let preIndex = (currentIndex - 1 + imageCount) % imageCount
        let preIndex1 = (currentIndex - 2 + imageCount) % imageCount
        
//        (scrollView.subviews[0] as! UIImageView).image = UIImage(named: "\(preIndex).png")
//        (scrollView.subviews[1] as! UIImageView).image = UIImage(named: "\(currentIndex).png")
//        (scrollView.subviews[2] as! UIImageView).image = UIImage(named: "\(nextIndex).png")
        if isLoadUrl {
            (scrollView.subviews[0] as! UIImageView).sd_setImage(with: urls[preIndex1])
            (scrollView.subviews[1] as! UIImageView).sd_setImage(with: urls[preIndex])
            (scrollView.subviews[2] as! UIImageView).sd_setImage(with: urls[currentIndex])
            (scrollView.subviews[3] as! UIImageView).sd_setImage(with: urls[nextIndex])
            (scrollView.subviews[4] as! UIImageView).sd_setImage(with: urls[nextIndex1])
        }
        else {
            (scrollView.subviews[0] as! UIImageView).image = images[preIndex1]
            (scrollView.subviews[1] as! UIImageView).image = images[preIndex]
            (scrollView.subviews[2] as! UIImageView).image = images[currentIndex]
            (scrollView.subviews[3] as! UIImageView).image = images[nextIndex]
            (scrollView.subviews[4] as! UIImageView).image = images[nextIndex1]
        }
        
    }
}

///UIScrollViewDelegate
extension BannerUseScrollView {
    @objc func didSelsctCurrent(tap:UITapGestureRecognizer) {
        if selBtnBack != nil {
            selBtnBack!(pageView.currentPage)
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
//        guard let _ = timer else {
//            return
//        }
        let maxscale : CGFloat = 0.86
       var px = scrollView.contentOffset.x - imagewidth*2
        if px > 0 {
            px = px > imagewidth ? imagewidth : px
            let curscale = 1 - px / imagewidth * (1.0-maxscale)
            self.scrollView.subviews[2].transform = CGAffineTransform(scaleX: curscale, y: curscale)
            let nextscale = maxscale + px / imagewidth * (1.0-maxscale)
            self.scrollView.subviews[3].transform = CGAffineTransform(scaleX: nextscale, y: nextscale)
        }
        else {
            px = -px
            px = px > imagewidth ? imagewidth : px
            let curscale = 1 - px / imagewidth * (1.0-maxscale)
            self.scrollView.subviews[2].transform = CGAffineTransform(scaleX: curscale, y: curscale)
            let prescale = maxscale + px / imagewidth * (1.0-maxscale)
            self.scrollView.subviews[1].transform = CGAffineTransform(scaleX: prescale, y: prescale)
        }
    }
    
    /// 开始滑动的时候，停止timer，设置为niltimer才会销毁
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        removeTimer()
    }
    
    /// 当停止滚动的时候重新设置三个ImageView的内容，然后悄悄滴显示中间那个imageView
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        reloadImage()
        scrollView.setContentOffset(CGPoint(x: imagewidth*2, y: 0), animated: false)
        self.scrollView.subviews[1].transform = CGAffineTransform(scaleX: 0.86, y: 0.86);
        self.scrollView.subviews[2].transform = CGAffineTransform(scaleX: 1, y: 1);
        self.scrollView.subviews[3].transform = CGAffineTransform(scaleX: 0.86, y: 0.86);
    }
    
    /// 停止拖拽，开始timer, 并且判断是显示上一个图片还是下一个图片
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        addTimer()
        
        if scrollView.contentOffset.x < imagewidth*2 {
            preImage()
        } else {
            nextImage()
        }
    }
}
